class QuestionnaireController < ApplicationController
	layout 'standard'
	
	def list
		sort = case params[:sort]
    when "questionnaire" then "questionnaire_names.name"
    when "youth_id" then "data_collections.youth_id"
    when "data_collection" then "data_collection_types.name"
    when "last_event" then "last_event"
    when "comment" then "comment"
    when "questionnaire_reverse" then "questionnaire_names.name DESC"
    when "youth_id_reverse" then "data_collections.youth_id DESC"
    when "data_collection_reverse" then "data_collection_types.name DESC"
    when "last_event_reverse" then "last_event DESC"
    when "comment_reverse" then "comment DESC"
		end
		
		
		post_sort = nil
		if (!sort.nil? && (sort.include?("last_event") || sort.include?("comment")))
			post_sort = sort
			sort = nil
		end
		
		if (sort.nil?)
			sort = "questionnaire_names.name"
		end
		

		
		@questionnaires = Questionnaire.find(:all, :include => [:questionnaire_name, {:data_collection, :data_collection_type}],
			:order => sort, :conditions => params[:questionnaire])
	
		if (!post_sort.nil?)
			if (post_sort.include?("last_event"))
				@questionnaires = @questionnaires.sort_by{|q| [q.get_last_event.nil? ? "" : q.get_last_event()[0]]} 			
			elsif (post_sort.include?("comment"))
				@questionnaires = @questionnaires.sort_by{|q| [q.get_last_event.nil? ? "" : q.get_last_event()[1]]} 			
			end
		
			if (post_sort.include?("DESC"))
				@questionnaires.reverse!
			end
		end
		
		# Manual filtering
		@questionnaires_copy = @questionnaires.clone
		
		if (!params[:last_event].nil?)
			@questionnaires_copy.each do |q|
				match = false
				last_event = q.get_last_event
				
				params[:last_event].each do |e|				
					if (!last_event.nil? && last_event[0] == e)						
						match = true
					end
				end
				
				if (!match)
					@questionnaires.delete(q)
				end					
			end
		end

		
		
		if request.xml_http_request?
			render :partial => "questionnaires_list", :layout => false
		end
	
	end
	
	
	def edit
		@questionnaire = Questionnaire.find(params[:id])
	end


  def new
    @questionnaire = Questionnaire.new
    
    @data_collection = DataCollection.find(params[:data_collection])
    @valid_questionnaires = Questionnaire.find_all_by_data_collection_id(@data_collection.id)

  end


  def create
    @questionnaire = Questionnaire.new(params[:questionnaire])

    default_save_procedure(@questionnaire)
  end


  def delete
    @questionnaire = Questionnaire.find(params[:questionnaire])
    @questionnaire.destroy

    redirect_to(:controller => 'data_collection', :action => 'edit', :id => @questionnaire.data_collection_id)
  end


end
